package com.wuliang.generate.api.filters;

import com.wuliang.generate.common.core.response.ResultUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 邬魉
 */
@Component
public class JwtTokenFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        Mono<DataBuffer> responseBody;
        String clientFlag = request.getHeaders().getFirst("ClientFlag");
        if (clientFlag == null) {
            responseBody = Mono.just(response.bufferFactory().wrap(ResultUtils.accessError().toBytes()));
            return response.writeWith(responseBody);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE - 2;
    }

    /**
     * 客户端标识
     */
    enum ClientFlag {

        /**
         * PC端
         */
        PC,
        /**
         * 移动端
         */
        MOBILE;
    }

}
